package io.alvin.ch03;

import java.util.concurrent.*;

/**
 * 自定义线程池和拒绝策略
 *
 * Created by Alvin on 2017/7/11.
 */
public class RejectThreadPoolDemo {

    public static class MyTask implements Runnable {

        @Override
        public void run() {
            System.out.println(System.currentTimeMillis() + ":Thread ID:" +
            Thread.currentThread().getId());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyTask task = new MyTask();
        /**
         * corePoolSize: 线程池中的线程数量
         * maximumPoolSize：线程池中的最大线程数量
         * keepAliveTime：当线程池中线程数量超过corePoolSize时，多余的空闲线程的存活时间
         * unit：keepAliveTime的单位
         * workQueue：任务队列，被提交但尚未被执行的任务。
         * threadFactory：线程工厂，用于创建线程，一般用默认的即可。
         * handler：拒绝策略。
         */
        ExecutorService es = new ThreadPoolExecutor(5, 5,
                0L, TimeUnit.MICROSECONDS,
                new LinkedBlockingDeque<>(10),
                Executors.defaultThreadFactory(),
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        System.out.println(r.toString() + " is discard");
                    }
                });
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            es.submit(task);
            Thread.sleep(10);
        }
    }
}
